package com.wink_172.activity

import android.app.Activity
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.Environment
import android.os.IBinder
import android.util.Log
import android.view.View
import androidx.databinding.DataBindingUtil
import com.alibaba.fastjson.JSON
import com.wink_172.commons.R
import com.wink_172.commons.databinding.ActivityMainBinding
import com.wink_172.library.LocalService
import com.wink_172.library.LocalService.MyBinder
import com.wink_172.library.activity.*
import com.wink_172.library.callback.ICallback
import com.wink_172.library.model.Constants
import com.wink_172.library.utils.*
import com.wink_172.library.utils.TencentCosUtils.uploadTectentFile
import com.wink_172.library.view.CustomToast.showToast
import org.xutils.common.Callback
import org.xutils.http.RequestParams
import org.xutils.x
import java.io.File
import java.math.BigDecimal


class MainActivity : SmartActivity() {
    lateinit var binding: ActivityMainBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setStatusBarLightMode(resources.getColor(R.color.transparent80), R.color.white)  //自定义颜色
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
        initView()
        StringListUtil.saveSingleString("123456", Constants.SEARCH_HISTORY)
//        Log.e(TAG, "StringList: ====>>" + StringListUtil.queryStringList(Constants.SEARCH_HISTORY)?.size)

        if (!checkPermissions(Constants.permissions)) {
            requestPermissions(Constants.ACTIVITY_REQUEST_CODE_PERMISSION, Constants.permissions)
        }





//        showProgressDialog(true,"舞蹈加载中",true)

//            com.wink_172.library.utils.CommonUtils.startSystemBrowser(
//                activity,
//                "https://fun4demo-1254407438.cos.ap-guangzhou.myqcloud.com/temp_fd/PCAM10.mp4"
//            )
//
//        TencentCosUtils.initTectentCosTempSing(
//            "AKIDI-oos4C3Zn8hbeQyX2e6PigKrQ5QboPivlCQaWS0ek6GmbRVp5rzIt4g7gbuFVlK",
//        "tYE9NWetMBw8Pzz1rVncwjKkGeiFxUUPdD7i21oN55w=",
//            "HMtKn1BDk5K2tuvpiUG70hFOmglTOitaaa8363e30cf66a7c305549af91562598qS4H-BC_Oao0bvCtZXidkWgyGo7HCsfm2YauhpUVrIS1ZjMDSyxvpsv70gW18HgA191NL9d5JGvkE9wwdfPgoow8ZzY12yzUANMRP6Y620uoq9nTFh87AKyvA96fe9KApV-KtYoHoJ3yD95eTWGiFAN6kKIj-cffXTY_9WagihH_3h1YECujZEPkAjFvatANoxA6jfXkhN5kXypQ5Og8UOJkRzizXBF0YHhzo4kqFRhx7obdv5-bHIXeDvv6ZZUWN4_OHvy4UmThOBrS6B3boplB9YyOFhUxdR7i3HFMYheT5fDXwUdNJFM6wFne3oJ-MWbEPYXGXFRWcKq1POeRm_3Ho2_QOssv4vvnhwNAL0ivh_BuOOeqtT-ZbdrDatcXmDSAdnDbrwTr-qfBBmMXoP0w3qMF03b02r76we_tOrr9rsnZq6Q37Cr5RdNF6aYid7XP9-qM_HZNxQiHQ9EFSND_VG7ygLiTrp4QfvxdI3HssPf5vPypBHhlRHG0riJGB0kXXyoMkpD5s3WIMrn3CkrlVERzFPiUDYNacG7oli6lw_MXR7az5AShR03m9h9Y",
//            1671158071,1671161671,
//          )
//        TencentCosUtils.initTectentCos(
//            "AKIDCIH7mIBxAIcDl76k3GS1TkrmVELx2K70",
//            "8JUYP4nPrAIEyVpwrZkkbFj071jGb5Oa",
//            "ap-guangzhou"
//        )

//        TencentCosUtils.initTectentCos(
//            "AKIDmSyJTRbnmeR5YpwmV4SjsukOtCJFbWsJ",
//            "ymitxqX4UlurcBYjjYBhVBi6KPL8mIer",
//        )
        bucket=Constants.BUCKET_TIANTIANTIAOWU;//请注意按需选择
//        bucket=Constants.BUCKET_WINK172;//请注意按需选择

        x.task().postDelayed(Runnable {

//            testuploadTencent()
        },3000)
        getTencentCosToken()

//        testgetFilename()

        //请注意一定要先有存储权限
//        CommonUtils.downLoadFile("https://static.hongbaodada.com/o_1f8rdspt6c6ugb41nbo3la1djg9.mp4?ci-process=snapshot&time=1888",
//            "/storage/emulated/0/Android/data/com.wink172.commons/cache/videodown"
//            ,
//            object :
//                com.wink_172.library.callback.ICallback {
//                override fun onSendEvent(event: Int, vararg args: Any?) {//这个callback用的非常巧妙
//
//                    when (event) {
//                        Constants.EventEnum.网络请求成功.ordinal-> {
//
//                        }
//                        Constants.EventEnum.网络请求错误.ordinal -> {
//
//                        }
//
//                        Constants.EventEnum.下载进度更新.ordinal-> {
//
//                        }
//
//
//                    }
//                }
//            }
//        )
    }

    fun testgetFilename(){
        val local_path="/storage/emulated/0/跳舞/dynamic_high_8XZ31671160284179.jpg"

        val str1=FileUtil.getFileName(local_path)
        val str2=FileUtil.getFileNameNoEx(local_path)
        val str3=FileUtil.getFileNameWithSuffix(local_path)
        val str4=FileUtil.getFileUrlName(local_path)
        val str5=FileUtil.getExtensionName(local_path)
        val str6=FileUtil.getFileEx(local_path)
        Log.e(TAG, "testgetFilename: ====>>"+str1 )
        Log.e(TAG, "testgetFilename: ====>>"+str2 )
        Log.e(TAG, "testgetFilename: ====>>"+str3 )
        Log.e(TAG, "testgetFilename: ====>>"+str4 )
        Log.e(TAG, "testgetFilename: ====>>"+str5)
        Log.e(TAG, "testgetFilename: ====>>"+str6)
    }

    /**
     * 腾讯云
     * */
    fun getTencentCosToken() {
        val params = RequestParams("http://ip:8081/config_action/config_detail?id=1")
//        Log.e(TAG, "getTencentToken: ====>>" + params.toString())

        val commonCallback: Callback.CommonCallback<*> = object : Callback.CommonCallback<String> {
            override fun onSuccess(result: String) {
//                Log.e(TAG, "getTencentToken: ====>>" + result)


            }

            override fun onError(ex: Throwable, isOnCallback: Boolean) {
//                Log.e(TAG, "getTencentToken: ====>>isOnCallback:" + isOnCallback)
//                com.nufang.zao.utils.CommonUtils.errorCallBack(
//                    params,
//                    ex,
//                    isOnCallback
//                )
            }

            override fun onCancelled(cex: Callback.CancelledException) {}
            override fun onFinished() {
            }
        }
        x.http().get(params, commonCallback)
    }

    var bucket=Constants.BUCKET_TIANTIANTIAOWU;
fun testuploadTencent(){
//    val test_file_path="/storage/emulated/0/Android/data/com.wink172.commons/cache/icon_offical_choice.png"
    val test_file_path="/sdcard/icon_offical_choice.png"
    val cosPath = ""+System.currentTimeMillis()+ "." +
            FileUtil.getExtensionName(test_file_path) //对象在存储桶中的位置标识符，即称对象键


    uploadTectentFile(cosPath, test_file_path,bucket,
        object : com.wink_172.library.callback.ICallback {
            override fun onSendEvent(event: Int, vararg objects: Any?) {
                if (event == Constants.EventEnum.上传成功.ordinal) {

                } else if (event == Constants.EventEnum.上传失败.ordinal) {
                }
            }
        }
    )
}




    fun getCachePath(context: Context): String? {
        var cachePath: String? = ""
        cachePath =
            if (Environment.MEDIA_MOUNTED == Environment.getExternalStorageState() || !Environment.isExternalStorageRemovable()) {
                //外部存储可用
                context.externalCacheDir!!.path
            } else {
                //外部存储不可用
                context.cacheDir.path
            }
        return cachePath
    }

    fun initView(){
        binding!!.btnControlList.setOnClickListener(this)
        binding!!.dynamicLayout.setOnClickListener(this)
        binding!!.btnAnimList.setOnClickListener(this)
        binding!!.btnNumberList.setOnClickListener(this)
        binding!!.btnDownList.setOnClickListener(this)
        binding!!.btnTestWeb.setOnClickListener(this)
        binding!!.btnUpload.setOnClickListener(this)
        binding!!.btnSelImages.setOnClickListener(this)
        binding!!.btnSelSingleImage.setOnClickListener(this)
        binding!!.btnSearchBar.setOnClickListener(this)

        binding!!.btnSwitchLang.setOnClickListener(this)
        binding!!.btnWeb.setOnClickListener(this)
        binding!!.btnDownload.setOnClickListener(this)
        binding!!.btnBlur.setOnClickListener(this)
        binding!!.btnFeedback.setOnClickListener(this)
        binding!!.btnTestActivity.setOnClickListener(this)
        binding!!.startService.setOnClickListener(this)
        binding!!.stopService.setOnClickListener(this)
        binding!!.bindService.setOnClickListener(this)
        binding!!.unbindService.setOnClickListener(this)
    }


    /**
     * 四舍五入，设置double，保留num位小数 */
    fun limitDouble2(d: Double, num: Int): String? {
        val d2 = String.format("%." + num + "f", d)
        return BigDecimal(d2).toString()
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != RESULT_OK) {
            return
        }
        when (requestCode) {
            Constants.ACTIVITY_REQUEST_CODE3001 -> {    //0简体    1英文    2繁体
                var pos: Int = data!!.getIntExtra(Constants.PARAM_DATA1, 0)

            }
        }
    }


    override fun onClick(v: View) {
        super.onClick(v)
        when (v.id) {

          R.id.dynamic_layout -> {
                DynamicLayoutActivity.startActivity(this)
            }
            R.id.btn_test_web -> {
                TestWebActivity.startActivity(this)
            }
            R.id. btn_number_list->{
                DecimalFormatActivity.startActivity(activity)
            }
            R.id.btn_anim_list -> {
              AnimActivity.startActivity(activity)
            }
            R.id.btn_down_list -> {
                DownListActivity.startActivity(this)
            }
            R.id.btn_upload -> {
                UploadActivity.startActivity(this)
            }

            R.id.btn_test_activity -> {

                TestActivity.startActivity(this)
            }

            R.id.btn_feedback -> FeedBackActivity.startActivity(this)
            R.id.btn_blur -> BlurActivity.startActivity(this)
            R.id.btn_switch_lang -> LanguageActivity.startActivity(
                this,
                Constants.ACTIVITY_REQUEST_CODE3001
            )
            R.id.btn_web -> WebActivity.startActivity(this, "标题", "https://www.baidu.com/")
            R.id.btn_download -> DownAppActivity.startActivity(this, Constants.APP_WEB_URL)
            R.id.btn_search_bar -> SearchBarActivity.startActivity(this)
            R.id.btn_sel_single_image -> SelectorSingleImageActivity.startActivity(this)
            R.id.btn_sel_images -> SelectorMultiImageActivity.startActivity(this)
            R.id.btn_control_list -> ControlActivity.startActivity(this)
            R.id.start_service -> {
                val startIntent = Intent(this, LocalService::class.java)
                startService(startIntent)
            }
            R.id.stop_service -> {
                val stopIntent = Intent(this, LocalService::class.java)
                isBound = false
                stopService(stopIntent)
            }
            R.id.bind_service -> {
                // android:process=":remote"   error
                //进程之间不能直接传递对象，传递的是该Binder对象的映射（代理对象）
                val bindIntent = Intent(this, LocalService::class.java)
                isBound = bindService(bindIntent, callback, BIND_AUTO_CREATE)
            }
            R.id.unbind_service -> {
                Log.e(TAG, "click Unbind Service button")
                if (isBound) {
                    unbindService(callback)
                    isBound = false
                }
            }
        }
    }

    private var myBinder: MyBinder? = null
    private var isBound = false

    /**
     * callback
     * */
    private val callback: ServiceConnection = object : ServiceConnection {
        override fun onServiceDisconnected(name: ComponentName) {}
        override fun onServiceConnected(name: ComponentName, service: IBinder) {
            myBinder = service as MyBinder
            myBinder!!.mCallback = object :
                com.wink_172.library.callback.ICallback {
                override fun onSendEvent(
                    event: Int,
                    vararg args: Any?
                ) {//这个callback用的非常巧妙    //这里因为不能传递非Serialiazable,对象 所以需要精简代码

                }
            }
            myBinder!!.startDownload()
        }
    }

    companion object {
        fun startActivity(context: Context, vararg args: Any?) {
            val intent = Intent(context, MainActivity::class.java)

            //intent.putExtra(Constants.PARAM_DATA1, (String) args[0]);
            context.startActivity(intent)
        }

        private const val TAG = "MainActivity"
    }
}